"""
AI提示词管理API路由
"""

from fastapi import APIRouter, Depends, HTTPException
from typing import Dict, Any

from ...core.security import get_current_user
from ...models.user import User
from ...core.prompts import (
    list_available_prompts,
    get_prompt_preview,
    get_prompt,
    get_system_prompt
)

router = APIRouter()


@router.get("/list")
async def list_prompts(
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """获取所有可用的提示词类型"""
    try:
        prompts = list_available_prompts()
        return {
            "success": True,
            "prompts": prompts,
            "total": len(prompts)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词列表失败: {str(e)}")


@router.get("/system")
async def get_system_prompt_api(
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """获取系统角色提示词"""
    try:
        system_prompt = get_system_prompt()
        return {
            "success": True,
            "prompt": system_prompt,
            "type": "system"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取系统提示词失败: {str(e)}")


@router.get("/preview/{prompt_type}")
async def preview_prompt(
    prompt_type: str,
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """预览指定类型的提示词模板"""
    try:
        prompt_template = get_prompt_preview(prompt_type)
        return {
            "success": True,
            "prompt_type": prompt_type,
            "template": prompt_template,
            "description": list_available_prompts().get(prompt_type, "未知类型")
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"预览提示词失败: {str(e)}")


@router.post("/format/{prompt_type}")
async def format_prompt(
    prompt_type: str,
    parameters: Dict[str, Any],
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """格式化指定类型的提示词"""
    try:
        formatted_prompt = get_prompt(prompt_type, **parameters)
        return {
            "success": True,
            "prompt_type": prompt_type,
            "formatted_prompt": formatted_prompt,
            "parameters": parameters
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"格式化提示词失败: {str(e)}")


@router.get("/example/{prompt_type}")
async def get_prompt_example(
    prompt_type: str,
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """获取提示词使用示例"""
    try:
        examples = {
            "requirement_analysis": {
                "parameters": {
                    "requirement_text": "用户登录功能：用户可以通过用户名和密码登录系统。"
                },
                "description": "需求分析需要提供requirement_text参数"
            },
            "test_case_generation": {
                "parameters": {
                    "requirement_text": "用户登录功能：用户可以通过用户名和密码登录系统。"
                },
                "description": "测试用例生成需要提供requirement_text参数"
            },
            "code_review": {
                "parameters": {
                    "code_content": "def login(username, password):\n    return username == 'admin' and password == '123456'"
                },
                "description": "代码审查需要提供code_content参数"
            },
            "api_documentation": {
                "parameters": {
                    "api_info": "POST /api/v1/auth/login - 用户登录接口"
                },
                "description": "API文档生成需要提供api_info参数"
            }
        }
        
        if prompt_type not in examples:
            raise ValueError(f"未知的提示词类型: {prompt_type}")
        
        example = examples[prompt_type]
        
        # 生成示例格式化结果
        formatted_example = get_prompt(prompt_type, **example["parameters"])
        
        return {
            "success": True,
            "prompt_type": prompt_type,
            "example": {
                "parameters": example["parameters"],
                "description": example["description"],
                "formatted_result": formatted_example[:500] + "..." if len(formatted_example) > 500 else formatted_example
            }
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词示例失败: {str(e)}")


@router.get("/config")
async def get_prompt_config(
    current_user: User = Depends(get_current_user)
) -> Dict[str, Any]:
    """获取提示词配置信息"""
    try:
        from ...core.config import settings
        
        config_info = {
            "custom_prompts_enabled": bool(
                settings.CUSTOM_SYSTEM_PROMPT or
                settings.CUSTOM_REQUIREMENT_ANALYSIS_PROMPT or
                settings.CUSTOM_TEST_CASE_GENERATION_PROMPT or
                settings.CUSTOM_CODE_REVIEW_PROMPT or
                settings.CUSTOM_API_DOCUMENTATION_PROMPT
            ),
            "available_customizations": {
                "system_prompt": bool(settings.CUSTOM_SYSTEM_PROMPT),
                "requirement_analysis": bool(settings.CUSTOM_REQUIREMENT_ANALYSIS_PROMPT),
                "test_case_generation": bool(settings.CUSTOM_TEST_CASE_GENERATION_PROMPT),
                "code_review": bool(settings.CUSTOM_CODE_REVIEW_PROMPT),
                "api_documentation": bool(settings.CUSTOM_API_DOCUMENTATION_PROMPT)
            },
            "configuration_method": "环境变量或.env文件",
            "supported_variables": [
                "CUSTOM_SYSTEM_PROMPT",
                "CUSTOM_REQUIREMENT_ANALYSIS_PROMPT",
                "CUSTOM_TEST_CASE_GENERATION_PROMPT",
                "CUSTOM_CODE_REVIEW_PROMPT",
                "CUSTOM_API_DOCUMENTATION_PROMPT"
            ]
        }
        
        return {
            "success": True,
            "config": config_info
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取配置信息失败: {str(e)}") 